import React from 'react';
import { WrapFormItem } from '@/plugins/form/form-components/common/form-item/formItem-decorate';
import { DatePicker } from '@/plugins/form/form-components/datepicker/view';
import { Props, State } from './interface';
import { Toast } from 'antd-mobile-v2';
import moment from 'moment';
const DatePickerWrap = WrapFormItem(DatePicker);
class RangeDatePicker extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
      startDate: '',
      endDate: ''
    };
  }
  componentDidMount() {
    setTimeout(() => {
      let { startTime, endTime } = this.props.form?.getFieldsValue();

      startTime = startTime ? moment(startTime).format('YYYY-MM-DD') : '';
      endTime = endTime ? moment(endTime).format('YYYY-MM-DD') : '';
      this.setState({
        startDate: startTime,
        endDate: endTime
      });
    });
  }

  startDateChange = (startDate?: string) => {
    const { form, code } = this.props;
    const endDate = form?.getFieldValue(code[1]);
    // 校验日期大小
    if (
      startDate &&
      (!endDate || moment(endDate).valueOf() >= moment(startDate).valueOf())
    ) {
      this.setState({
        startDate
      });
      form?.setFieldsValue({
        [code[0]]: startDate
      });
    } else {
      Toast.fail('开始时间必须小于结束时间');
    }
  };

  endDateChange = (endDate?: string) => {
    const { form, code } = this.props;
    const startDate = form?.getFieldValue(code[0]);
    // 校验日期大小
    if (
      endDate &&
      (!startDate || moment(startDate).valueOf() <= moment(endDate).valueOf())
    ) {
      this.setState({
        endDate
      });
      form?.setFieldsValue({
        [code[1]]: endDate
      });
    } else {
      Toast.fail('结束时间必须大于开始时间');
    }
  };

  public render() {
    const { startDate, endDate } = this.state;
    const { maxDate, form, code } = this.props;
    form?.getFieldProps(code[0]);
    form?.getFieldProps(code[1]);
    const initStartDate = startDate
      ? moment(startDate).toDate()
      : moment().toDate();
    const initEndDate = endDate ? moment(endDate).toDate() : moment().toDate();
    return (
      <>
        <DatePickerWrap
          value={startDate}
          initValue={initStartDate}
          maxDate={maxDate}
          required={this.props.required}
          onChange={this.startDateChange}
          name={this.props.name[0]}
        />
        <DatePickerWrap
          value={endDate}
          initValue={initEndDate}
          maxDate={maxDate}
          required={this.props.required}
          onChange={this.endDateChange}
          name={this.props.name[1]}
        />
      </>
    );
  }
}

export default RangeDatePicker;
